#!/bin/sh
# original script developed by Jordi Moraleda
# converted to sh script and AIX by Nestor Lafon-Gracia

# avoiding calling it while creating a screen
# on aix the the terminal defeault screen terminal is vt100
if [ "$TERM" = "screen" -o  "$TERM" = "vt100" ]; then
   exit
fi

# Get screen sessions
ATTACHED=`screen -ls | grep "(Attached)" | awk '{print $1}'`
DETACHED=`screen -ls | grep "(Detached)" | awk '{print $1}'`

echo "Current screen options..."
echo

echo "  0:  No screen"

n=1
for scrName in $ATTACHED; do
   echo "  $n:  Reattach to $scrName"
   cmd[$n]="screen -DRR $scrName"
   n=`expr $n + 1`
done

for scrName in $DETACHED; do
   echo "  $n:  Attach to $scrName"
   cmd[$n]="screen -r $scrName"
   n=`expr $n + 1`
done

echo "  $n:  Create a new screen"
echo

out=$(uname)
if [ "$out" != "AIX" ]; then
   alias echo="echo -e"
fi

# Read option
option=""
while [ -z "$option" ]  || [ "$option" -lt "0" -o "$option" -gt "$n" ]; do
   echo "> \c"
   read option
done

# No screen?
if [ "$option" -eq "0" ]; then 
   exit
fi

# New screen?
if [ "$option" -eq "$n" ]; then
   while [ -z "$name" ]; do
      echo "Name for the screen: \c "
      #echo -n "Name for the screen:  "
      read name
   done
   cmd[$n]="screen -S $name"
fi

# Run screen
if [ ! -z "${cmd[$option]}" ]; then
   exec ${cmd[$option]}
fi

